﻿using Clipper.BLL;
using Clipper.Model.DataBaseModel;
using ClipperBaseUI.Controls;
using Global;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Clipper.ClipperWindow
{
    /// <summary>
    /// WinStandardCurveData.xaml 的交互逻辑
    /// </summary>
    public partial class WinStandardCurveData : BaseWindow
    {
        public WinStandardCurveData()
        {
            InitializeComponent();
        }
        BLL.DataBaseBLL.StandardCurveData bll = new BLL.DataBaseBLL.StandardCurveData();  //创建逻辑层对象
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void BaseWindow_Loaded(object sender, RoutedEventArgs e)
        {
            DetectItems detectItem = new DetectItems();
            //if (mKitModel.ReagentModel1 != null)
            //{
            comboBox.ItemsSource = detectItem.GetModelList("");
        }
        BLL.DataBaseBLL.StandardCurveData standardBll = new BLL.DataBaseBLL.StandardCurveData();

        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //点击此处查找浓度
            Model.DetectItems detectItem = comboBox.SelectedItem as Model.DetectItems;
            if (standardBll.CheckExist(detectItem.detectItem))
            {
                StandardCurveData standard = standardBll.GetModel(detectItem.detectItem);
                if (standard.Concentration1 != 0)
                {
                    textBox.Text = standard.Concentration1.ToString();
                }
                if (standard.Concentration2 != 0)
                {
                    textBox2.Text = standard.Concentration2.ToString();
                }
                if (standard.Concentration3 != 0)
                {
                    textBox4.Text = standard.Concentration3.ToString();
                }
                if (standard.Concentration4 != 0)
                {
                    textBox6.Text = standard.Concentration4.ToString();
                }
                if (standard.Concentration5 != 0)
                {
                    textBox8.Text = standard.Concentration5.ToString();
                }
                if (standard.Concentration6 != 0)
                {
                    textBox10.Text = standard.Concentration6.ToString();
                }

                textBox12.Text = standard.CloseDate.ToString();
                textBox13.Text = standard.BatchNumber.ToString();
            }
            else
            {
                //不含有检测项要提示一下
                WinNoticeNoDetectItem winNoDetectItem = new WinNoticeNoDetectItem(); //声明窗口
                winNoDetectItem.ShowDialog();
            }
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            List<double> concentrationLogList = new List<double>();//对数集合
            List<double> detectResultLogList = new List<double>();//对数集合

            List<double> concentrationList = new List<double>(); //普通集合
            List<double> detectResultList = new List<double>();  //普通集合

            StandardCurveData model = new StandardCurveData();
            Model.DetectItems detectItem = (Model.DetectItems)comboBox.SelectedItem;
            if (detectItem == null)
            {
                WinStandardCurveNotice win = new WinStandardCurveNotice();
                win.ShowDialog();
                return;
            }
            else
            {
                model.DetectItem = detectItem.detectItem;
            }
            //浓度1设置
            if (textBox.Text.Trim().Equals(""))
            {
                model.Concentration1 = 0;
            }
            else
            {
                model.Concentration1 = Convert.ToDouble(textBox.Text);
                concentrationLogList.Add(Math.Log10(Convert.ToDouble(textBox.Text)));
                concentrationList.Add(Convert.ToDouble(textBox.Text));
            }
            if ((textBox1.Text.Trim()).Equals(""))
            {
                model.DetectResult1 = 0;
            }
            else
            {
                model.DetectResult1 = Convert.ToDouble(textBox1.Text);
                detectResultLogList.Add(Math.Log10(Convert.ToDouble(textBox1.Text)));
                detectResultList.Add(Convert.ToDouble(textBox1.Text));
            }
            //浓度2设置
            if ((textBox2.Text.Trim()).Equals(""))
            {
                model.Concentration2 = 0;
            }
            else
            {
                model.Concentration2 = Convert.ToDouble(textBox2.Text);
                concentrationLogList.Add(Math.Log10(Convert.ToDouble(textBox2.Text)));
                concentrationList.Add(Convert.ToDouble(textBox2.Text));
            }
            if ((textBox3.Text.Trim()).Equals(""))
            {
                model.DetectResult2 = 0;
            }
            else
            {
                model.DetectResult2 = Convert.ToDouble(textBox3.Text);
                detectResultLogList.Add(Math.Log10(Convert.ToDouble(textBox3.Text)));
                detectResultList.Add(Convert.ToDouble(textBox3.Text));
            }
            //浓度3设置
            if ((textBox4.Text.Trim()).Equals(""))
            {
                model.Concentration3 = 0;
            }
            else
            {
                model.Concentration3 = Convert.ToDouble(textBox4.Text);
                concentrationLogList.Add(Math.Log10(Convert.ToDouble(textBox4.Text)));
                concentrationList.Add(Convert.ToDouble(textBox4.Text));

            }
            if ((textBox5.Text.Trim()).Equals(""))
            {
                model.DetectResult3 = 0;
            }
            else
            {
                model.DetectResult3 = Convert.ToDouble(textBox5.Text);
                detectResultLogList.Add(Math.Log10(Convert.ToDouble(textBox5.Text)));
                detectResultList.Add(Convert.ToDouble(textBox5.Text));
            }
            //浓度4设置
            if ((textBox6.Text.Trim()).Equals(""))
            {
                model.Concentration4 = 0;
            }
            else
            {
                model.Concentration4 = Convert.ToDouble(textBox6.Text);
                concentrationLogList.Add(Math.Log10(Convert.ToDouble(textBox6.Text)));
                concentrationList.Add(Convert.ToDouble(textBox6.Text));
            }
            if ((textBox7.Text.Trim()).Equals(""))
            {
                model.DetectResult4 = 0;
            }
            else
            {
                model.DetectResult4 = Convert.ToDouble(textBox7.Text);
                detectResultLogList.Add(Math.Log10(Convert.ToDouble(textBox7.Text)));
                detectResultList.Add(Convert.ToDouble(textBox7.Text));
            }

            //浓度5设置
            if ((textBox8.Text.Trim()).Equals(""))
            {
                model.Concentration5 = 0;
            }
            else
            {
                model.Concentration5 = Convert.ToDouble(textBox8.Text);
                concentrationLogList.Add(Math.Log10(Convert.ToDouble(textBox8.Text)));
                concentrationList.Add(Convert.ToDouble(textBox8.Text));
            }

            if ((textBox9.Text.Trim()).Equals(""))
            {
                model.DetectResult5 = 0;
            }
            else
            {
                model.DetectResult5 = Convert.ToDouble(textBox9.Text);
                detectResultLogList.Add(Math.Log10(Convert.ToDouble(textBox9.Text)));
                detectResultList.Add(Convert.ToDouble(textBox9.Text));
            }
            //浓度6设置
            if ((textBox10.Text.Trim()).Equals(""))
            {
                model.Concentration6 = 0;
            }
            else
            {
                model.Concentration6 = Convert.ToDouble(textBox10.Text);
                concentrationLogList.Add(Math.Log10(Convert.ToDouble(textBox10.Text)));
                concentrationList.Add(Convert.ToDouble(textBox10.Text));
            }
            if ((textBox11.Text.Trim()).Equals(""))
            {
                model.DetectResult6 = 0;
            }
            else
            {
                model.DetectResult6 = Convert.ToDouble(textBox11.Text);
                detectResultLogList.Add(Math.Log10(Convert.ToDouble(textBox11.Text)));
                detectResultList.Add(Convert.ToDouble(textBox11.Text));
            }
            if (!textBox12.Text.Trim().Equals(""))
            {
                model.CloseDate = DateTime.Parse(textBox12.Text.Trim());
            }

            if (!textBox13.Text.Trim().Equals(""))
            {
                model.BatchNumber = Convert.ToInt32(textBox13.Text.Trim());
            }
            if (textBox12.Text.Trim().Equals("")|| textBox13.Text.Trim().Equals(""))
            {
                WinNoticeNoEmpty win = new WinNoticeNoEmpty();
                win.ShowDialog();
                return;
            }


            List < double > logCoefficientB = ServiceProvider.Algorithmclass.setCoefficientB(concentrationLogList, detectResultLogList);
            List<double> ordinaryCeofficientB = ServiceProvider.Algorithmclass.setCoefficientB(concentrationList, detectResultList);

            model.FileTime = DateTime.Now;
            model.LineValue = ServiceProvider.Algorithmclass.getLineValue(concentrationLogList, detectResultLogList);  //计算对数相关系数值
            model.OrdinaryLineValue = ServiceProvider.Algorithmclass.getLineValue(concentrationList, detectResultList); //计算普通相关系数值
            model.CoefficientB = logCoefficientB[2];                                 //计算对数回归线性方程系数（b） 
            model.ConstantA = Math.Round(logCoefficientB[1] - logCoefficientB[2] * logCoefficientB[0], 3);//计算对数回归线性方程常数（a）
            model.OrdinaryCoefficientB = ordinaryCeofficientB[2];                          //计算普通回归方程系数（b）
            model.OrdinaryConstantA = Math.Round(ordinaryCeofficientB[1] - ordinaryCeofficientB[2] * ordinaryCeofficientB[1], 3);//计算普通回归方程常数（a）

            List<StandardCurveData> models = bll.GetAllStandardDetectItem();
            int count = 0;
            foreach (StandardCurveData scmodel in models)
            {
                if (model.DetectItem.Equals(scmodel.DetectItem))
                {
                    bll.updateStandardCurveData(model);
                    count++;
                    break;
                }
            }
            if (count == 0)
            {
                bll.insertStandardCurveModel(model);
            }
            this.Close();//关闭窗口
        }


        /// <summary>
        /// m_x是检测浓度 ，m_y是检测结果
        /// </summary>
        /// <param name="m_x"></param>
        /// <param name="m_y"></param>
        /// <returns></returns>
        /// 
        double xAverage = 0; // x的平均数
        double yAverage = 0;  // y的平均数
        public double getLineValue(List<double> m_x, List<double> m_y) //  m_x是检测浓度 ，m_y是检测结果
        {

            double X = 0;
            foreach (double concentration in m_x)
            {
                X += concentration;
            }

            double y = 0;
            foreach (double detectResult in m_y)
            {
                y += detectResult;  //检测结果集合
            }
            xAverage = X / m_y.Count;  // x的平均数
            yAverage = y / m_y.Count;  // y的平均数

            double countResult = 0; //表达式上面的结果
            double reagentGan = 0;  //表达式下面的结果
            double yreagentGan = 0;
            for (int i = 0; i < m_y.Count; i++)
            {
                countResult += (m_x[i] - xAverage) * (m_y[i] - yAverage);
                reagentGan += Math.Pow((m_x[i] - xAverage), 2);
                yreagentGan += Math.Pow((m_y[i] - yAverage), 2);
            }
            return Math.Pow((countResult / Math.Sqrt(reagentGan * yreagentGan)), 2);

            //int r =∑(Xi - X的平均数)(Yi - Y平均数) / 根号下[∑(Xi - X平均数) ^ 2 *∑(Yi - Y平均数) ^ 2]
        }


        /// <summary>
        /// 计算系数b的值
        /// </summary>
        /// <param name="m_x"></param>
        /// <param name="m_y"></param>
        /// <returns></returns>
        public List<double> setCoefficientB(List<double> m_x, List<double> m_y) //m_x是检测浓度集合 ，m_y是检测结果集合
        {
            List<double> resultList = new List<double>();

            double X = 0;
            foreach (double concentration in m_x)
            {
                X += concentration;
            }

            double y = 0;
            foreach (double detectResult in m_y)
            {
                y += detectResult;  //检测结果集合
            }

            double xAverage = X / m_y.Count;  // x的平均数
            double yAverage = y / m_y.Count;  // y的平均数
            resultList.Add(xAverage);
            resultList.Add(yAverage);

            double topCount = 0;
            double bottomCount = 0;
            for (int j = 0; j < m_x.Count; j++)
            {
                topCount += (m_x[j] - xAverage) * (m_y[j] - yAverage);
                bottomCount += Math.Pow((m_x[j] - xAverage), 2);
            }
            resultList.Add(topCount / bottomCount);
            return resultList;
        }

    }
}
